package dao.daoImp;

import bean.ClassBean;
import dao.IClassDao;

import java.sql.SQLException;


public class ClassDaoImp extends BaseDao implements IClassDao {
    //建立班级表
    @Override
    public void createClass() {
        this.setConnection();
        try {
            ps = con.prepareStatement("CREATE TABLE t_class(" +
                    "pk_classId INT PRIMARY KEY AUTO_INCREMENT," +
                    "c_className VARCHAR(20)" +
                    ");");

            ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }
    }

    @Override
    public void add(ClassBean classBean) {
        this.setConnection();

        try {
            ps = con.prepareStatement("INSERT INTO t_class(pk_classId,c_className)" +
                    "values (?,?)");

            ps.setObject(1, classBean.getClassId());
            ps.setObject(2, classBean.getClassName());

            ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }
    }

    @Override
    public ClassBean findById(int id) {
        this.setConnection();
        try {
            ps = con.prepareStatement("select * from t_class where pk_classId=?");
            ps.setObject(1, id);

            rs=ps.executeQuery();

            if (rs.next()) {
                ClassBean classBean = new ClassBean();
                classBean.setClassId(rs.getInt("pk_classId"));
                classBean.setClassName(rs.getString("c_className"));
                return classBean;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }
        return null;
    }
}

